package com.fjrz.bbxwj.main.host

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.KEY_NAME_UUID_IMEI
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.main.access.AccessActivity
import com.fjrz.bbxwj.main.host.side.*
import com.fjrz.bbxwj.main.video.CameraActivity
import com.fjrz.bbxwj.mode.vm.CommonViewModel
import com.fjrz.bbxwj.util.AudioMngHelper
import com.fjrz.bbxwj.util.HttpWebSocketUtils
import com.fjrz.bbxwj.util.LocationUtils
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.view.DialogHintPopup
import com.module.lemlin.view.LoginAuthPopup
import com.tbruyelle.rxpermissions3.RxPermissions
import kotlinx.android.synthetic.main.activity_access_2.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.include_main_body.*
import org.greenrobot.eventbus.EventBus


class MainActivity : ViewModeActivity<CommonViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, MainActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
        override fun onFragmentResumed(fm: FragmentManager, fragment: Fragment) {
            super.onFragmentResumed(fm, fragment)
            when (fragment) {
                is MainHomeFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                    drawerMainBody.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                }
                is MainCityFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                    drawerMainBody.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                }
                is MainMsgFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (true))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                    drawerMainBody.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                }
                is MainMineFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (true))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                    drawerMainBody.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
                }
            }
        }
    }

    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                val intent = Intent(Intent.ACTION_DIAL)
                val data: Uri = Uri.parse("tel:0591-888888")
                intent.data = data
                startActivity(intent)
            },
            onCancel = {
                hintPopup.dismiss()
            })
    }

    override fun viewModel(): CommonViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun stateBar(): StatusBar {
        return StatusBar(
            bottomColor = R.color.colorWhite
        )
    }

    override fun initView() {

        val only = "${
            Settings.System.getString(
                contentResolver, Settings.Secure.ANDROID_ID
            )
        }${Build.FINGERPRINT}"
        SPStaticUtils.put(KEY_NAME_UUID_IMEI, EncryptUtils.encryptMD5ToString(only))

        val fragments: MutableList<Fragment> = mutableListOf(
            MainHomeFragment.newInstance(),
            MainCityFragment.newInstance(),
            MainMsgFragment.newInstance(),
            MainMineFragment.newInstance()
        )

        vpMainBody.apply {
            setScrollAnim(false)
        }.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment = fragments[position]

            override fun getCount(): Int = fragments.size

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) = Unit
        }
        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks, (true)
        )

        rbMainBottomHome.setOnClickListener {
            vpMainBody.currentItem = 0
        }

        rbMainBottomCate.setOnClickListener {


            val rxPermission = RxPermissions(this)
            rxPermission.request(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe { permission ->
                if (!permission) {
                    toast(message = "请到设置中开启位置权限")
                    if (vpMainBody.currentItem == 0) {
                        rbMainBottomHome.isChecked = true
                    } else if (vpMainBody.currentItem == 1) {
                        rbMainBottomCate.isChecked = true
                    } else if (vpMainBody.currentItem == 2) {
                        rbMainBottomMsg.isChecked = true
                    } else if (vpMainBody.currentItem == 3) {
                        rbMainBottomMine.isChecked = true
                    }
                } else {
                    LocationUtils.location(
                        this, object : LocationUtils.OnSubAdminAreaListener {
                            override fun onSubAdminArea(adminArea: String?, subAdminArea: String?) {
                                if (adminArea.isNullOrEmpty())
                                    return
                                if (subAdminArea.isNullOrEmpty())
                                    return
                                viewModel.commonDevice(adminArea, subAdminArea)
                            }
                        })
                    vpMainBody.currentItem = 1
                }
            }
        }

        rbMainBottomMsg.setOnClickListener {
            if (RZApplication.token().isNullOrEmpty()) {
                if (vpMainBody.currentItem == 0) {
                    rbMainBottomHome.isChecked = true
                } else if (vpMainBody.currentItem == 1) {
                    rbMainBottomCate.isChecked = true
                }
                AccessActivity.open(activity = this)
            } else {
                vpMainBody.currentItem = 2
                EventBus.getDefault().post("stop")
            }
        }

        rbMainBottomMine.setOnClickListener {
            if (RZApplication.token().isNullOrEmpty()) {
                if (vpMainBody.currentItem == 0) {
                    rbMainBottomHome.isChecked = true
                } else if (vpMainBody.currentItem == 1) {
                    rbMainBottomCate.isChecked = true
                }
                AccessActivity.open(activity = this)
            } else {
                vpMainBody.currentItem = 3
                EventBus.getDefault().post("stop")
            }
        }

        ivMainVideoRecord.setOnClickListener {
            val rxPermissions = RxPermissions(this)
            rxPermissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
            ).subscribe {
                if (!it) {
                    toast(message = "请到设置中开启相关权限")
                } else if (RZApplication.token().isNullOrEmpty()) {
                    AccessActivity.open(activity = this)
                } else {
                    CameraActivity.open(activity = this)
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun initData() {
        if (!RZApplication.token().isNullOrEmpty()) {
            HttpWebSocketUtils.instance()
        }
    }

    override fun initViewMode() {
        viewModel.commonPhoneLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            response?.httpData?.data?.let {
                hintPopup.setText(
                    textTitle = "联系客服",
                    textMessage = "0591-888888",
                    textConfirm = "拨打",
                    textCancel = "取消"
                ).showPopupWindow()
            }
        })
    }

    override fun onEventMainThread(any: Any) {
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_GO) {
            AccessActivity.open(activity = this)
        } else if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            HttpWebSocketUtils.instance()
        }
    }

    override fun onBackPressed() {
        if (drawerMainBody.isDrawerOpen(GravityCompat.END)) {
            drawerMainBody.closeDrawers()
        } else {
            super.onBackPressed()
        }
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.ivMainMineSide -> {
                drawerMainBody.openDrawer(GravityCompat.END)
            }
            //视频/私人草稿箱
            R.id.tvMainSketchPrivate -> {
                MainSketchBoxActivity.open(activity = this, title = "私人草稿箱", type = 2)
            }
            R.id.tvMainSketchVideo -> {
                MainSketchBoxActivity.open(activity = this, title = "视频草稿箱", type = 1)
            }
            //设置
            R.id.tvMainSetting -> {
                MainSettingActivity.open(activity = this)
            }
            //设置
            R.id.tvMainFeedback -> {
                MainFeedbackActivity.open(activity = this)
            }
            //我的关注
            R.id.tvMainAttention -> {
                MainAttentionActivity.open(activity = this)
            }
            //数据总览
            R.id.tvMainOverview -> {
                MainOverviewActivity.open(activity = this)
            }
            //联系客服
            R.id.tvMainContact -> {
                viewModel.commonData()
            }
            //我的作品
            R.id.tvMainWorks -> {
                MainWorksActivity.open(activity = this)
            }
        }
    }

}